<template>
  <div class="shop-contact-table">
    <div v-if="isEdit" class="btns">
      <el-button type="primary" @click="handleAdd">添加</el-button>
      <el-button type="primary" @click="handleRemove">删除</el-button>
    </div>
    <table-box ref="tableBox" show-index class="table-height-auto" :data="tableData" :table-config="tableConfig" @selection-change="handleSelectionChange">
      <el-table-column v-if="isEdit" slot="before" type="selection" :selectable="selectableFunc" />
    </table-box>
  </div>
</template>
<script>
function genRow() {
  return {
    accountCode: '', //	业务账号编码
    accountName: '', //	业务账号名称
    address: '', //	联系人地址
    changeCode: '', //	变更单号
    changeType: '', //	变更类型
    contactFax: '', //	联系人传真
    contactId: '', //	联系人ID
    contactPhone: '', //	联系人手机
    contactProperty: '', //	联系人性质
    contactScope: '3', //	联系人范围（1客户、2业务账号、3门店）
    contactTel: '', //	联系人电话
    contactTypeCode: '', //	联系人类别编码
    contactTypeName: '', //	联系人类别名称
    customerCode: '', //	客户编码
    email: '', //	联系人邮箱
    isAutoAdd: '1', //	是否默认新增 0 否 1是
    isBefore: '', //	数据来源1:MDM,0:CTM
    isChange: '1', //	是否变更
    name: '', //	联系人姓名
    shopBusinessId: '', //	门店id
    shopCode: '' //	门店编码
  }
}
export default {
  name: 'ShopContactTable',
  props: {
    tableData: {
      type: Array,
      default: () => []
    },
    shopData: {
      type: Array,
      default: () => []
    },
    isEdit: {
      type: Boolean,
      default: true
    },
    customerCode: {
      type: String,
      default: undefined
    },
    isAudit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      auditSetting: [
        {
          prop: 'shopCode',
          label: '门店编码',
          minWidth: 200,
          required: this.isEdit,
          render: (h, row) => {
            if (!this.checkRowEdit(row)) {
              return h('span', row.shopCode)
            }
            const children = this.shopSelectedData.map(e => {
              return h('el-option', {
                props: {
                  value: e.code,
                  label: e.name
                },
                key: e.code
              })
            })

            return h('el-select', {
              props: {
                value: row.shopCode,
                clearable: true,
                filterable: true
              },
              attrs: {
                clearable: true
              },
              on: {
                input: v => {
                  this.$set(row, 'shopCode', v)
                  const t = this.shopSelectedData.find(e => e.code === v)
                  this.$set(row, 'shopName', t ? t.name : '')
                }
              }
            }, children)
          }
        },
        {
          prop: 'shopName',
          label: '门店名称',
          minWidth: 140
        }
      ],
      tableConfig: {
        hideFuncBar: true,
        setting: [
          {
            prop: 'shopAddress',
            label: '门店详细地址',
            minWidth: 200,
            required: this.isEdit,
            render: (h, row) => {
              if (!this.checkRowEdit(row) || ![1, '1'].includes(row.isAutoAdd)) {
                return h('span', row.shopAddress)
              }
              const children = this.shopSelectedData.map(e => {
                return h('el-option', {
                  props: {
                    value: e.shopBusinessId,
                    label: e.originalShopAddr
                  },
                  key: e.originalCode
                })
              })

              return h('el-select', {
                props: {
                  value: row.shopBusinessId,
                  clearable: true,
                  filterable: true
                },
                on: {
                  input: v => {
                    this.$set(row, 'shopBusinessId', v)
                    if (!v) {
                      this.$set(row, 'shopAddress', '')
                      return
                    }
                    const t = this.shopSelectedData.find(e => e.shopBusinessId === v)
                    this.$set(row, 'shopAddress', t.shopAddr)
                  }
                }
              }, children)
            }
          },
          {
            prop: 'name',
            label: '联系人姓名',
            minWidth: 140,
            required: this.isEdit,
            render: (h, row) => {
              if (!this.checkRowEdit(row)) {
                return h('span', {}, row.name)
              }
              return h('el-input', {
                props: {
                  value: row.name,
                  clearable: true,
                  placeholder: '请输入'
                },
                attrs: {
                  clearable: true
                },
                on: {
                  input: v => this.$set(row, 'name', v)
                },
                nativeOn: {
                  click: e => e.stopPropagation()
                }
              })
            }
          },
          {
            prop: 'contactTypeCode',
            label: '联系人类别',
            minWidth: 200,
            required: this.isEdit,
            render: (h, row) => {
              if (!this.checkRowEdit(row)) {
                return h('span', row.contactTypeName)
              }
              return h('c-common-search-mdm', {
                props: {
                  value: row.contactTypeCode,
                  label: row.contactTypeName,
                  placeholder: '请选择',
                  custDocCode: 'QY019'
                },
                on: {
                  input: v => this.$set(row, 'contactTypeCode', v),
                  'update:label': v => this.$set(row, 'contactTypeName', v)
                },
                nativeOn: {
                  click: e => e.stopPropagation()
                }
              })
            }
          },
          {
            prop: 'contactTel',
            label: '联系人电话',
            minWidth: 200,
            render: (h, row) => {
              if (!this.checkRowEdit(row)) {
                return h('span', {}, row.contactTel)
              }
              return h('el-input', {
                props: {
                  value: row.contactTel,
                  clearable: true,
                  placeholder: '请输入'
                },
                attrs: {
                  clearable: true
                },
                on: {
                  input: v => this.$set(row, 'contactTel', v)
                },
                nativeOn: {
                  click: e => e.stopPropagation()
                }
              })
            }
          },
          {
            prop: 'contactPhone',
            label: '联系人手机',
            minWidth: 200,
            required: this.isEdit,
            render: (h, row) => {
              if (!this.checkRowEdit(row)) {
                return h('span', {}, row.contactPhone)
              }
              return h('el-input', {
                props: {
                  value: row.contactPhone,
                  clearable: true,
                  placeholder: '请输入'
                },
                attrs: {
                  clearable: true
                },
                on: {
                  input: v => this.$set(row, 'contactPhone', v)
                },
                nativeOn: {
                  click: e => e.stopPropagation()
                }
              })
            }
          },
          {
            prop: 'contactFax',
            label: '联系人传真',
            minWidth: 200,
            render: (h, row) => {
              if (!this.checkRowEdit(row)) {
                return h('span', {}, row.contactFax)
              }
              return h('el-input', {
                props: {
                  value: row.contactFax,
                  clearable: true,
                  placeholder: '请输入'
                },
                attrs: {
                  clearable: true
                },
                on: {
                  input: v => this.$set(row, 'contactFax', v)
                },
                nativeOn: {
                  click: e => e.stopPropagation()
                }
              })
            }
          },
          {
            prop: 'email',
            label: '联系人邮箱',
            minWidth: 200,
            // required: this.isEdit,
            render: (h, row) => {
              if (!this.checkRowEdit(row)) {
                return h('span', {}, row.email)
              }
              return h('el-input', {
                props: {
                  value: row.email,
                  clearable: true,
                  placeholder: '请输入'
                },
                attrs: {
                  clearable: true
                },
                on: {
                  input: v => this.$set(row, 'email', v)
                },
                nativeOn: {
                  click: e => e.stopPropagation()
                }
              })
            }
          },
          {
            prop: 'address',
            label: '联系人地址',
            minWidth: 200,
            render: (h, row) => {
              if (!this.checkRowEdit(row)) {
                return h('span', {}, row.address)
              }
              return h('el-input', {
                props: {
                  value: row.address,
                  clearable: true,
                  placeholder: '请输入'
                },
                attrs: {
                  clearable: true
                },
                on: {
                  input: v => this.$set(row, 'address', v)
                },
                nativeOn: {
                  click: e => e.stopPropagation()
                }
              })
            }
          }
        ]
      },
      selectionRows: []
    }
  },
  computed: {
    shopSelectedData() {
      return this.shopData.filter(e => [1, '1'].includes(e.isNewBusinessTakeover))
    }
  },
  watch: {
    shopSelectedData: {
      handler(v) {
        if (this.isAudit) { return }
        for (let i = 0; i < this.tableData.length; i++) {
          const c = this.tableData[i]
          if (!c.shopBusinessId) {
            if (![1, '1'].includes(c.isAutoAdd)) {
              this.tableData.splice(i, 1)
              i--
              continue
            }
          } else if (v.every(e => e.shopBusinessId !== c.shopBusinessId)) {
            if ([1, '1'].includes(c.isAutoAdd)) {
              this.$set(c, 'shopAddress', '')
              this.$set(c, 'shopBusinessId', '')
            } else {
              this.tableData.splice(i, 1)
              i--
            }
          }
        }

        // for (const t of this.tableData) {
        //   if (this.isAudit) {
        //     // if (!v.some(e => e.code === t.shopCode)) {
        //     //   this.$set(t, 'shopCode', '')
        //     //   this.$set(t, 'shopName', '')
        //     // }
        //   } else {
        //     if (!v.some(e => e.shopBusinessId === t.shopBusinessId)) {
        //       this.$set(t, 'shopAddress', '')
        //       this.$set(t, 'shopBusinessId', '')
        //     }
        //   }
        // }
      },
      deep: true
    },
    isAudit: {
      handler(v) {
        if (this.isAudit) {
          const i = this.tableConfig.setting.findIndex(e => e.prop === 'shopAddress')
          if (i >= 0) {
            this.__backItem = this.tableConfig.setting[i]
            this.tableConfig.setting.splice(i, 1, ...this.auditSetting)
          }
        } else {
          const i = this.tableConfig.setting.findIndex(e => e.prop === this.auditSetting[0].prop)
          if (i >= 0) {
            this.tableConfig.setting.splice(i, this.auditSetting.length, this.__backItem)
          }
        }
      },
      immediate: true
    }
  },
  created() {

  },
  methods: {
    checkRowEdit(row) {
      return this.isEdit && !row.isMdm
    },
    selectableFunc(row, index) {
      return [1, '1'].includes(row.isAutoAdd)
    },
    validate() {
      return new Promise((resolve, reject) => {
        if (!this.isEdit) return resolve(true)
        const requireds = this.tableConfig.setting.filter(e => e.required)
        const msgs = []
        // 格式校验
        const rules = {
          contactTel: { label: '联系人电话', rule: v => {
            if (!/^(\d{3,4}-?)?\d{7,8}$|^\d{11}$/.test(v)) {
              return '格式有误'
            }
          } },
          contactPhone: {
            label: '联系人手机',
            rule: v => {
              if (!/^\d{11}$/.test(v)) {
                return '格式有误'
              }
            }
          }
          // email: {
          //   label: '联系人邮箱',
          //   rule: v => {
          //     if (!/^[\d\w]+@[\d\w]+(\.[\d\w]+)+$/.test(v)) {
          //       return '格式有误'
          //     }
          //   }
          // }
        }
        const rulesKV = Object.entries(rules)
        for (let i = 0; i < this.tableData.length; i++) {
          const t = this.tableData[i]
          for (const r of requireds) {
            if (t[r.prop] === '' || t[r.prop] === undefined || t[r.prop] === null) {
              msgs.push(`【门店联系人】第${i + 1}行【${r.label}】未选择或未填写`)
            }
          }
          for (const [k, v] of rulesKV) {
            if (t[k] !== '' && t[k] !== undefined && t[k] !== null) {
              const m = v.rule(t[k])
              if (m) {
                msgs.push(`【门店联系人】第${i + 1}行【${v.label}】${m}`)
              }
            }
          }
        }
        if (msgs.length > 0) {
          this.$message({
            type: 'warning',
            message: msgs.join('<br>'),
            dangerouslyUseHTMLString: true
          })
          reject(false)
          return
        }
        // 至少有一条联系人类别为“责任人”的数据
        const shopBusinessIds = new Set(this.tableData.map(e => e.shopBusinessId))
        const typeErrMsgs = []
        shopBusinessIds.forEach(shopBusinessId => {
          if (!this.tableData.filter(e => e.shopBusinessId === shopBusinessId).some(e => [1, '1'].includes(e.contactTypeCode))) {
            const t = this.tableData.find(e => e.shopBusinessId === shopBusinessId)
            typeErrMsgs.push(`【门店联系人】门店 ${t.shopAddress} 至少要有一条【联系人类别】为【责任人】的数据`)
            return
          }
        })
        if (typeErrMsgs.length > 0) {
          this.$message({
            type: 'warning',
            message: typeErrMsgs.join('<br>'),
            dangerouslyUseHTMLString: true
          })
          reject(false)
          return
        }
        resolve(true)
      })
    },
    handleAdd() {
      this.tableData.push(genRow())
    },
    handleRemove() {
      if (!this.singleJudge(this.selectionRows, '删除')) {
        return
      }
      if (this.selectionRows.some(e => ![1, '1'].includes(e.isAutoAdd))) {
        this.$message.warning(`由门店带出的联系人不可删除`)
        return
      }
      // 判断自动带出，自能删除手动新增的
      this.selectionRows.forEach(e => {
        const i = this.tableData.indexOf(e)
        if (i >= 0) {
          this.tableData.splice(i, 1)
        }
      })
      this.selectionRows = []
    },
    handleSelectionChange(v) {
      this.selectionRows = v
    },
    getData() {
      return this.tableData.map(e => {
        e = this.$deepClone(e)
        e.contactScope = 3
        return e
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.shop-contact-table{
  .btns{

  }
}
</style>
